<template>
	<div class="box" id="rightCont">
	<!-- main -->
	<div class="main" id="main">
			<!-- 一般用于右侧表格 -->
			<div class="main-right">
				<!-- 表格下搜索 下拉 时间选择按钮事件等 -->
				<div class="main-icon">
					<div class="main-icon-a">
						<i class="el-icon-xy"
							style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #409EFF;color: #fff;"></i>
						<span style="font-size: 16px;font-weight:300;margin-left: 12px;">{{CatalogueName}}</span>
					</div>
					<!-- btn1 -->
					<div class="main-icon-b">
						<span style="font-size: 12px;color: #606266;font-weight: bold;">状态：</span>
						<el-dropdown @command="handleCommand" trigger="click">
							<span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
							<el-dropdown-menu slot="dropdown">
							  <el-dropdown-item command="a">可用</el-dropdown-item>
							  <el-dropdown-item command="b">禁用</el-dropdown-item>
							  <el-dropdown-item command="c" divided>全部</el-dropdown-item>
							</el-dropdown-menu>
					    </el-dropdown>
					</div>
					<!-- btn2 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
						<el-input size="mini" placeholder="编码、名称、拼音简码" suffix-icon="el-icon-key" v-model="searchValue"></el-input>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
				<!-- 表格主题 -->
				<div class="table" id="form">
					<el-table 
					  :data="tableData" 
					  ref="singleTable"
					  border 
					  @row-dblclick="handledbRow"
					  highlight-current-row 
					  @current-change="handleCurrentTableChange">
						<el-table-column prop="id" label="库存序号" width="68" align="center"></el-table-column>
						<el-table-column prop="tcmtype" label="药品类型" width="88">
							<template slot-scope="{ row }">
								<!-- 根据state显示不同的图标 -->
								<i :class="tcmIconMap[row.tcmtype]" :style="{ color: tcmColorMap[row.tcmtype] }"></i>
								<span>{{ tcmMap[row.tcmtype] || '' }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="dosform" label="药品剂型">
							<template slot-scope="{ row }">
								<!-- 根据state显示不同的图标 -->
								<i :class="statusIconMap[row.dosform]" :style="{ color: statusColorMap[row.dosform] }"></i>
								<span>{{ statusMap[row.dosform] || '' }}</span>
							</template>
						</el-table-column>
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index"></el-table-column>
					</el-table>
				</div>
				<!-- feet -->
				<div class="feet">
					<!-- 分页 -->
					<el-pagination
					style="margin: 12px;"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageNum"
					:page-sizes="[20,50,100]"
					:page-size="pageSize"
					:total="totalSize"
					layout="total, sizes, prev, pager, next, jumper"
					background>
					</el-pagination>
				</div>
				<!-- feet -->
				<div class="feet" id="feet">
					<div class="feetBtn">
						<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="small" plain
							@click="feetHandClick(i)" style="margin-left: 12px;">{{ v.title }}
						</el-button>
					</div>
				</div>
			</div>
		</div>
		<!-- 流向记录 -->
		<div class="flowdiglog">
			<el-dialog
			  :title="'【' + flowDialogTitle + '】' + '药品流向记录'"
			  :visible.sync="flowdiglog"
			  width="58%"
			  top="28px"
			  :before-close="flowhandleClose">
			  <div class="innerModel-header">
			  	<!-- dateTimer -->
			  	<span>业务日期:</span>
			  	<el-date-picker v-model="startDate" type="datetime" size="mini" style="margin-left: 8px;" placeholder="选择开始时间"
			  		:picker-options="pickerOptions" @change="startDateHandle" value-format="yyyy-MM-dd HH:mm:ss"> 
			  	</el-date-picker>
			  	<el-date-picker v-model="endDate" type="datetime" style="margin-left: 8px;" size="mini" placeholder="选择结束时间"
			  		:picker-options="pickerOptions" @change="endDateHandle" value-format="yyyy-MM-dd HH:mm:ss">
			  	</el-date-picker>
			  	<el-button size="mini" type="primary" plain @click="changeData" style="margin-left: 8px;">刷新</el-button>
			  </div>
			  <div class="innerModel-table" style="margin-top: 8px;">
			  	<el-table :data="innertableData" v-loading="loading" ref="singleTable" border @row-dblclick="handledbRow"
			  		highlight-current-row @current-change="handleCurrentTableChange">
			  		<!-- 表格行rows  -->
			  		<el-table-column prop="id" label="系统序号"></el-table-column>
					<el-table-column prop="drugName" label="药品名称"></el-table-column>
					
					<el-table-column prop="shedId" label="入库库房">
						 <template slot-scope="{ row }">
							<span>{{ shedIdMap[row.shedId] || '未知' }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="bizSouc" label="业务来源">
						 <template slot-scope="{ row }">
							<span :style="{ color: bizColorMap[row.bizSouc] }">{{ bizMap[row.bizSouc] || '未知' }}</span>
						</template>
					</el-table-column>
			  		<el-table-column v-for="(col, inx) in innertableDataRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="flowdiglogColumnWidth(col, innertableData)"></el-table-column>
			  		<!-- fixed -->
			  		<el-table-column fixed="left" label="行号" type="index" width="48" align="center"></el-table-column>
			  	</el-table>
			  	<!-- 分页 -->
			  	<el-pagination
			  	style="margin: 12px;"
			  	@size-change="innerHandleSizeChange"
			  	@current-change="innerHandleCurrentChange"
			  	:current-page="pageNum"
			  	:page-sizes="[10, 20, 50]"
			  	:page-size="innerPageSize"
			  	:total="innerTotolSize"
			  	layout="total, sizes, prev, pager, next, jumper"
			  	background
			  	>
			  	</el-pagination>
			  </div>
			  <span slot="footer" class="dialog-footer">
			    <el-button size="mini" type="primary" @click="flowdiglog = false">查看单据</el-button>
			    <el-button size="mini" type="primary" @click="flowdiglog = false">打印</el-button>
				<el-button size="mini" type="primary" @click="flowdiglog = false">关闭</el-button>
			  </span>
			</el-dialog>
		</div>
		
		<div class="print-template-container">
		    <!-- <print-template-designer /> -->
		</div>
		
		<div class="xqAbout">
			<el-dialog
			  title="中药库存批次明细"
			  :visible.sync="XQdialogVisible"
			  :fullscreen="true"
			  :show-close="false"
			  :before-close="XQhandleClose">
			  <div class="xqTable">
				<el-table :data="XQtableData" v-loading="loading" ref="singleTable" border highlight-current-row @current-change="TZXQhandleCurrent">
					<!-- 表格行rows  -->
					<el-table-column prop="id" label="库存序号" width="88"></el-table-column>
<!-- 					<el-table-column prop="shedId" label="当前诊所" width="128">
						 <template slot-scope="{ row }">
							<span>{{ shedIdMap[row.shedId] || '未知' }}</span>
						</template>
					</el-table-column> -->
					<el-table-column prop="shedId" label="入库库房" width="88">
						 <template slot-scope="{ row }">
							<span>{{ shedIdMap[row.shedId] || '未知' }}</span>
						</template>
					</el-table-column>
					
					<el-table-column prop="code" label="药品编码" width="168"></el-table-column>
					<el-table-column prop="drugId" label="药品序号" width="88"></el-table-column>
					<el-table-column prop="drugName" label="药品名称" width="168"></el-table-column>
					<el-table-column prop="drugSpec" label="规格描述" width="168"></el-table-column>
<!-- 					<el-table-column prop="drugName" label="药品类型" width="88"></el-table-column> -->
					<el-table-column prop="dosForm" label="药品剂型" width="88"></el-table-column>
					
					<el-table-column prop="prodentpName" label="生产厂家" width="168"></el-table-column>
					<el-table-column prop="manuLotnum" label="生产批号" width="128"></el-table-column>
					<el-table-column prop="manuDate" label="生产日期" width="128"></el-table-column>
					<el-table-column prop="expyDate" label="有效日期" width="128"></el-table-column>
					<el-table-column prop="purcPric" label="成本单价" width="98"></el-table-column>
					<el-table-column prop="purcAmt" label="成本金额" width="98"></el-table-column>
					<el-table-column prop="salePric" label="零售单价" width="98"></el-table-column>
					<el-table-column prop="saleAmt" label="零售金额" width="98"></el-table-column>
					
					<el-table-column prop="purcCnt" label="库存数量" width="128"></el-table-column>
					<el-table-column prop="drugName" label="药品单位" width="78"></el-table-column>
					<el-table-column prop="bizSouc" label="供货单位" width="128">
						 <template slot-scope="{ row }">
							<span :style="{ color: bizColorMap[row.bizSouc] }">{{ bizMap[row.bizSouc] || '未知' }}</span>
						</template>
					</el-table-column>
					<!-- <el-table-column v-for="(col, inx) in innertableDataRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="flowdiglogColumnWidth(col, innertableData)"></el-table-column> -->
					<!-- fixed -->
					<el-table-column fixed="left" label="行号" type="index" width="48" align="center"></el-table-column>
				</el-table>
				<!-- 分页 -->
				<el-pagination
				style="margin: 12px;"
				@size-change="innerHandleSizeChange"
				@current-change="innerHandleCurrentChange"
				:current-page="pageNum"
				:page-sizes="[10, 20, 50]"
				:page-size="innerPageSize"
				:total="innerTotolSize"
				layout="total, sizes, prev, pager, next, jumper"
				background
				>
				</el-pagination>
			  </div>
			  <div class="XQfeetBtn">
			  	<el-button v-for="(v,i) in XQfeetBtn" :key="i" :type="v.type" :disabled="v.disabled" plain
			  	:loading="loading" :icon="v.icon" size="mini" @click="XQfeetHandClick(v)">{{ v.title }}</el-button>
			  </div>
			</el-dialog>
			<!-- 有效期调整Model -->
			<div class="toolExaDate">
				<el-dialog
				  :title="ToolExaDateTitle"
				  :visible.sync="TZXQdialogVisible"
				  width="28%"
				  :before-close="TZXQhandleClose">
				<el-descriptions class="margin-top" title="" :column="3" size="mini" border>
				    <el-descriptions-item>
				      <template slot="label">
				        <!-- <i class="el-icon-user"></i> -->
				        药品名称
				      </template>
				      {{ this.TZXQcurrentTable.drugName }}
				    </el-descriptions-item>
				    <el-descriptions-item>
				      <template slot="label">
				        <!-- <i class="el-icon-mobile-phone"></i> -->
				        药品规格
				      </template>
				      {{ this.TZXQcurrentTable.drugName }}
				    </el-descriptions-item>
				    <el-descriptions-item>
				      <template slot="label">
				        <i class="el-icon-location-outline"></i>
				        生产批号
				      </template>
				      {{ this.TZXQcurrentTable.manuLotnum }}
				    </el-descriptions-item>
				    <el-descriptions-item>
				      <template slot="label">
				        <i class="el-icon-office-building"></i>
				        生产厂家
				      </template>
				      {{ this.TZXQcurrentTable.prodentpName }}
				    </el-descriptions-item>
				  </el-descriptions>
				  <!-- 开始调整选择新的有效期 -->
				  <div class="newDate" style="display: flex;margin-top: 8px;">
				    <!-- 生产日期 -->
				    <el-date-picker 
				      size="mini" 
				      v-model="TZXQcurrentTable.manuDate" 
				      type="date" 
				      placeholder="生产日期"
				      value-format="yyyy-MM-dd"
				      @change="handleManuDateChange">
				    </el-date-picker>
				    
				    <el-date-picker 
				      size="mini" 
				      v-model="TZXQcurrentTable.expyDate" 
				      type="date" 
				      placeholder="有效日期"
				      value-format="yyyy-MM-dd"
				      @change="handleExpyDateChange">
				    </el-date-picker>
				  </div>
				  <span slot="footer" class="dialog-footer">
					<el-button size="mini" plain type="primary" @click="TZXQSubmit">确 定</el-button>
					<el-button size="mini" plain @click="TZXQdialogVisible = false">取 消</el-button>
				  </span>
				</el-dialog>
			</div>
		</div>
		
	</div>
</template>

<script>
	// selfs / js
	// import PrintTemplateDesigner from '@/components/PrintTemplateDesigner.vue';
	// 接口
	import { getBatchNumber,getExpyDate,updateDate } from "@/api/systemCatalogue/traMedici.js";
	
	import { pageList,purcRetnPages } from "@/api/systemCatalogue/traMedici.js";
	
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			// PrintTemplateDesigner
		},
		data() {
			return {
				// 树菜单Props
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				windowWidth:'', //右侧表格动态宽度
				searchValue:'',
				CatalogueName:'[中药库]药品库存',
				DropDownedName:'可用',
				iconComes:'el-icon-byj',
				flowDialogTitle:'',
				manuLotnum:'', // 批号
				startDate:'', // * 开始时间
				endDate:'', // * 结束时间
				flowId:'',
				// boolean
				disabled:true,
				getdisabled:true,
				XQdialogVisible:false,
				loading:false,
				flowdiglog:false,
				addDialogVisible:false, // 新增控制
				editDialogVisible:false, // 编辑控制
				TZXQdialogVisible:false, // 药品有效日期调整Model
				ToolExaDateTitle:'药品有效日期调整',
				// number
				idx: 0,
				pageNum: 1, //当前页currentPage
				pageSize: 20,
				totalSize: 20, //总条数
				innerPageSize: 10,
				innerTotolSize: 20, //总条数
				/* obj */
				addForm:{}, // form表单 新增 * 
				editForm:{}, // form表单 修改 * 
				// arr
				data: [],
				userInfo: [],
				tableData: [],
				// currentTable:[],
				currentTable: {}, // 初始化为空对象
				TZXQcurrentTable:[],
				innertableData:[],
				XQtableData:[],
				TypeOption:[
					{ id:1,label:'中药',value:'中药'},{ id:2,label:'中成药',value:'中成药'},
					{ id:3,label:'卫材',value:'卫材'},{ id:4,label:'血液',value:'血液'},
					{ id:5,label:'疫苗',value:'疫苗'},{ id:9,label:'中药',value:'中药'}
				],
				MarkOption:[{ id:1,label:'比例加成',value:'比例加成'},{ id:2,label:'固定加成',value:'固定加成'}], //加成比例
				formType:[], // 表单头部内容
				statusOption:[{ id:0,label:'禁用',value:'禁用'},{ id:1,label:'可用',value:'可用'}],
				// title右侧按钮
				headerBtn:[
				 { refesh:"refesh", title:"刷新", type:"", icon:"el-icon-refresh" },
				 { senior:"senior", title:"高级", type:"primary", icon:"" },
				],
				feetBtn:[
				 { refesh:"refesh", title:"批次号显示", type:"primary", icon:"el-icon-upload2" },
				 // { refesh:"refesh", title:"流向记录", type:"primary", icon:"el-icon-printer" },
				 { refesh:"refesh", title:"打印", type:"primary", icon:"el-icon-finished" },
				 { refesh:"refesh", title:"关闭", type:"primary", icon:"el-icon-close" },
				 ],
				 XQfeetBtn:[
				 { refesh:"refesh", title:"档案信息", type:"primary", icon:"el-icon-upload2" },
				 { refesh:"refesh", title:"流向记录", type:"primary", icon:"el-icon-printer" },
				 { refesh:"refesh", title:"日期调整", type:"primary", icon:"el-icon-finished" },
				 { refesh:"refesh", title:"打印", type:"primary", icon:"el-icon-close" },
				 { refesh:"refesh", title:"关闭", type:"primary", icon:"el-icon-close" },
				 ],
				// title右侧按钮
				tableRows:[
					{ name:"药品名称", prop:"name", type:""},
					{ name:"药品编码", prop:"code", type:"" },
					{ name:"规格描述", prop:"drugSpec", type:"" },
					
					{ name:"库存数量", prop:"purcCnt"},{ name:"成本单价", prop:"purcPric", type:"" },
					{ name:"成本金额", prop:"purcAmt" },
					{ name:"零售单价", prop:"salePric", type:"" },{ name:"零售金额", prop:"saleAmt", type:"" },
					{ name:"生产厂家", prop:"prodentpName", type:"" },{ name:"生产批号", prop:"manuLotnum", type:"" },
					
				],
				innertableDataRows:[
					{ name:"创建时间", prop:"createTime", type:""},
					{ name:"库存变化数量", prop:"chgCnt", type:""},
					{ name:"变化前库", prop:"agoCnt", type:"" },{ name:"变化后库", prop:"afrCnt", type:"" },
					{ name:"计量单位", prop:"unt", type:"" },{ name:"成本单价", prop:"purcPric", type:"" },
					{ name:"零售单价", prop:"salePric", type:"" },{ name:"药品规格", prop:"drugSpec", type:"" },
					{ name:"生产厂家", prop:"prodentpName", type:"" },{ name:"生产批号", prop:"manuLotnum", type:"" },
				],
				bizMap:{
					1: '采购入库',
					2: '其他入库',
					3: '赠送入库',
					4: '盘点入库',
					5: '系统切换入库',
					6: '冲销',
					7: '调拨',
					8: '出库',
					9: '盘点反结转',
					10: '退药',
					11: '采购退库',
					12: '报损出库',
					13: '过期出库',
					14: '捐赠出库',
					15: '其他出库',
					16: '输错出库',
					17: '科室出库',
					18: '销售出库',
					19: '拆零自动出库',
				},
				bizColorMap: {
					1: '#67C23A',
					2: '#409EFF',
					3: '#F56C6C',
					4: '#FF6700',
					5: '#aa0000',
					6: '#F56C6C',
					7: '#FF6700',
					8: '#67C23A',
					9: '#aa0000',
				},

				//props
				shedIdMap:{
					1: '西药库',
					2: '中药库',
				},
				statusMap: {
					1: '饮片',
					2: '颗粒',
				},
				statusIconMap: {
					1: 'el-icon-tlzt',
					2: 'el-icon-kangshengsu',
				},
				statusColorMap: {
					1: '#409EFF',
					2: '#F56C6C',
				},

				tcmMap: {
					1: '植物类药',
					2: '动物类药',
					3: '金石矿物类药',
				},
				tcmIconMap: {
					1: 'el-icon-jxdy',
					2: 'el-icon-wsthjzp',
					3: 'el-icon-yl',
				},
				tcmColorMap: {
					1: '#67C23A',
					2: '#F56C6C',
					3: '#E6A23C',
				},
				// 表单验证规则
				addFormRules:{},
				elTree:[
					{ label: '全部', path:'', title:'', icon:'el-icon-news',
						children:[
							{ id:1,label: '中药',path:'',title:'中药',icon:'el-icon-xy'},
							{ id:2,label: '中成药',path:'',title:'中成药',icon:'el-icon-zhongchengyao'},
							{ id:3,label: '中草药',path:'',title:'中草药',icon:'el-icon-zhongcaoyao'},
							{ id:4,label: '民族药',path:'',title:'民族药',icon:'el-icon-xyzp'},
							{ id:5,label: '卫材',path:'',title:'卫材',icon:'el-icon-xyjhtxyyzhy'},
							{ id:6,label: '血液',path:'',title:'血液',icon:'el-icon-blood'},
							{ id:7,label: '疫苗',path:'',title:'疫苗',icon:'el-icon-yimiaoke'},
							{ id:8,label: '检验试剂',path:'',title:'检验试剂',icon:'el-icon-tjxg'},
							{ id:9,label: '营养',path:'',title:'营养',icon:'el-icon-cnyyyy'},
						],
					},
				],
				pickerOptions: {
				  shortcuts: [
					{ text: '今天', onClick(picker) { picker.$emit('pick', new Date()); }}, 
					{ text: '昨天', onClick(picker) { const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24);picker.$emit('pick', date);}}, 
					{ text: '一周前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);picker.$emit('pick', date);}},
					{ text: '最近一个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);picker.$emit('pick', date);}},
					{ text: '最近三个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);picker.$emit('pick', date);}},
					{ text: '半年前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 180);picker.$emit('pick', date);}},
					{ text: '去年',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 360);picker.$emit('pick', date);}},
					]
				},
			};
		},
		mounted() {
			this.loadData();
			this.getForm();
			this.getDateTime();
			//获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
			})
			// 定义数据来源
			// this.formType = AccType.map(function(val) { return val })
		},
		methods: {
			/*
				数据源
			*/
			async loadData() {
			  this.loading = true;
			  try {
			    let res = await pageList({
			      pageNum: this.pageNum,
			      pageSize: this.pageSize,
			      dosform: '',
			      drugName: '',
			      drugType: ''
			    });
			
			    if (res.code === 200) {
			      // 处理数据，将 pacUntCnt 和 dosUntCnt 分别与 pacUnt 和 dosUnt 相加
			      this.tableData = res.data.content.map(item => {
			        return {
			          ...item,
			          pacUntCnt: (item.pacUntCnt || 0) + (item.pacUnt || 0)  + (item.dosUntCnt || 0) + (item.dosUnt || 0),
			        };
			      });
			      
			      this.totalSize = res.data.totalSize;
			    } else {
			      this.$message.error(res.message || '获取数据失败');
			    }
			  } catch (error) {
			    this.$message.error('请求出错: ' + error.message);
			  } finally {
			    this.loading = false;
			  }
			},
			// 挂载或销毁前后重新赋值后端参数
			getForm(){
				// 左侧提交表单
				// this.addForm = addForm.map(v => {return v })[0]; // Form
				// this.editForm = addForm.map(v => {return v })[0]; // Form
				// 解构赋值排除 list 属性 => 弃用
				// this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
			},
			/*
				about tree
			*/
			handleNodeClick(data,e) {
				this.CatalogueName = data.title
				this.iconComes = 'el-icon-' + this.makePy(data.label)
				console.log(this.iconComes);
				this.loadData();
			},
			// add
			addSubmit(){

			},
			// 获取当前(今天)的时间 从 00:00:00 - 23:59:59
			getDateTime(){
				const today = new Date();
				// 设置开始时间为今天00:00:00
				const startDate = new Date(today);
				startDate.setHours(0, 0, 0, 0);
				this.startDate = this.formatDateTime(startDate);
				// 设置结束时间为今天23:59:59
				const endDate = new Date(today);
				endDate.setHours(23, 59, 59, 999);
				this.endDate = this.formatDateTime(endDate);
			},
			// 辅助方法：格式化日期时间为yyyy-MM-dd HH:mm:ss格式
			formatDateTime(date) {
			    const year = date.getFullYear();
			    const month = String(date.getMonth() + 1).padStart(2, '0');
			    const day = String(date.getDate()).padStart(2, '0');
			    const hours = String(date.getHours()).padStart(2, '0');
			    const minutes = String(date.getMinutes()).padStart(2, '0');
			    const seconds = String(date.getSeconds()).padStart(2, '0');
			    
			    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			// editSubmit
			async editSubmit(){
				//触发验证表单
				this.$refs.editForm.validate(async(valid) => {
				  if(valid){
					//验证通过
					console.log(this.editForm);
					let res = await updatedocMark(this.editForm)
					console.log(res);
					if (res.code === 200){
					this.$message({
						message:res.message,
						type:"success"
					});
					this.editDialogVisible = false
					this.loadData(); //更新数据驱动
					}else{
					  // 失败
					  this.$message({ type: 'error', message: 'fail!'});
					}
				}
				});
			},
			
			/*
				about table
			*/
			// 表单头部聚焦事件 => addForm
			async sname(val,i) {
				// val.id = i;
				this.idx = i;
				// i event
				switch (i) {
					
				}
			},
			// SelectVal to editForm
			handleChange(val){
				// i event
				switch (this.idx) {
					case 1: 
						if(val === 1){
							this.formType[5].disabled = false
							this.formType[6].disabled = true
							// this.addForm.markUpPric = ''
							// this.disabled = true
						}else if(val === 2){
							this.formType[5].disabled = true
							this.formType[6].disabled = false
							// this.addForm.markUpRate = ''
						}
					break;
				}
			},
			// 开始时间变化值
			startDateHandle(value) {
				if (value) {
					// 使用 JavaScript 的 Date 对象格式化日期
					this.startTime = value
					console.log(this.startTime,'startTimestartTimestartTime');
				} else {
					this.startTime = '';
				}
			},
			// 结束时间变化值
			endDateHandle(value){
				if (value) {
				  // 使用 JavaScript 的 Date 对象格式化日期
				  this.endTime = value
				} else {
					this.endTime = '';
				}
			},
			
			// 修改 getFlowData 方法，添加参数验证
			async getFlowData() {
			  // 验证必要参数
			  if (!this.flowId || !this.manuLotnum) {
			    this.$message.error('缺少必要参数');
			    return;
			  }
			  
			  try {
			    this.loading = true;
			    let res = await purcRetnPages({ 
			      drugId: this.flowId,
			      manuLotnum: this.manuLotnum,
			      pageNum: this.pageNum,
			      pageSize: this.innerPageSize,
			      startTime: this.startDate,
			      endTime: this.endDate
			    });
			    
			    if (res.code === 200) {
			      this.innertableData = res.data.content;
			      this.innerTotolSize = res.data.totalSize;
			    } else {
			      this.$message.error(res.message || '获取流向记录失败');
			    }
			  } catch (error) {
			    console.error('获取流向记录出错:', error);
			    this.$message.error('获取流向记录出错');
			  } finally {
			    this.loading = false;
			  }
			},
			// 内层刷新按钮
			changeData(){
				this.getFlowData();
			},
			// db events
			handledbRow(row, column, event){
				// console.log(this.addForm);
			},
		   // col 里面包含了表头字段和名称，list 是表格数据
		   columnWidth(col, list) {
				let prop = col.prop,lab = col.lab;
				let width = 20; // 设定一个最小值
				let maxlenStr = ""; // 最长字符串
				for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		        }
		        width = Math.max(width, len(lab), len(maxlenStr));
		        // 表格自带的内边距(20px) 自调
		        return width + 12; // 这里加了 12px
		        function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 8;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 12;
		             // 英文大写字符 8px
		             else if ("A" <= char && char <= "Z") length += 8;
					 // 数字
					 else if (Number.isFinite(Number(char))) length += 8;
		             // 中文字符 28px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 14;
		             // 其他 8px
		             else length += 12;
		           }
		           return length;
		        }
		    },
			flowdiglogColumnWidth(col, list) {
				let prop = col.prop,lab = col.lab;
				let width = 20; // 设定一个最小值
				let maxlenStr = ""; // 最长字符串
				for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		        }
		        width = Math.max(width, len(lab), len(maxlenStr));
		        // 表格自带的内边距(20px) 自调
		        return width + 12; // 这里加了 12px
		        function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 8;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 8;
		             // 英文大写字符 8px
		             else if ("A" <= char && char <= "Z") length += 8;
					 // 数字
					 else if (Number.isFinite(Number(char))) length += 8;
		             // 中文字符 28px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
		             // 其他 8px
		             else length += 12;
		           }
		           return length;
		        }
		    },
			// 表格单选
			handleCurrentTableChange(val){
				this.currentTable = val
			},
			
			// 修改 TZXQhandleCurrent 方法
			TZXQhandleCurrent(val) {
			  this.TZXQcurrentTable = val;
			  // 同时更新 flowId 和 manuLotnum
			  if (val) {
			    this.flowId = val.drugId;
			    this.manuLotnum = val.manuLotnum;
			  }
			  console.log('当前选中行:', this.TZXQcurrentTable);
			},
			// 获取批次号数据
			async getBatchNumberData() {
			  try {
			    this.loading = true;
			    const res = await getBatchNumber({
			      drugId: this.currentTable.drugId
			    });
			    
			    if (res.code === 200) {
			      this.XQtableData = res.data;
			      this.XQdialogVisible = true;
			    } else {
			      this.$message.error(res.message || '获取批次号数据失败');
			    }
			  } catch (error) {
			    console.error('获取批次号数据出错:', error);
			    this.$message.error('获取批次号数据出错');
			  } finally {
			    this.loading = false;
			  }
			},
			// see table
			// 表格底部循环按钮事件
			feetHandClick(i){
				// i event
				switch (i) {
					case 0:
					// 批次号显示
					  if (!this.currentTable || Object.keys(this.currentTable).length === 0) {
						this.$message.warning('请先选择一条数据');
						return;
					  }
					  
					  // 高亮显示选中的行
					  this.$nextTick(() => {
						const table = this.$refs.singleTable;
						if (table) {
						  table.setCurrentRow(this.currentTable);
						}
					  });
					  
					  // 调用接口获取批次号数据
					  this.getBatchNumberData();
					  break;
					case 1:
					// 流向记录
						this.$message({ type: 'warning', message: '流向记录'});
					break;
					case 2:
						this.handlePrint();
					break;
					case 3:
						this.$message({ type: 'warning', message: '暂未开放，敬请期待。'});
					break;
				}
			},
			
			// 修改流向记录按钮点击逻辑
			XQfeetHandClick(v) {
			  console.log(v,'日期调整等按钮');
			  if(v.title == '档案信息' || v.title.includes('档案信息')){
			    this.$message({ type: 'warning', message: '档案信息'});
			  }
			  else if(v.title == '流向记录' || v.title.includes('流向记录')){
			    // 确保有选中行
			    if (!this.TZXQcurrentTable || Object.keys(this.TZXQcurrentTable).length === 0) {
			      this.$message.warning('请先选择一条批次数据');
			      return;
			    }
			    
			    // 直接从当前选中行获取值
			    this.manuLotnum = this.TZXQcurrentTable.manuLotnum;
			    this.flowId = this.TZXQcurrentTable.drugId;
			    this.flowDialogTitle = this.TZXQcurrentTable.drugName;
			    this.flowdiglog = true;
			    this.getFlowData();	
			  }
			  else if(v.title == '日期调整' || v.title.includes('日期调整')){
			    if (!this.TZXQcurrentTable || Object.keys(this.TZXQcurrentTable).length === 0) {
			      this.$message.warning('请先选择一条批次数据');
			      return;
			    }
			    this.TZXQdialogVisible = true;
			  }
			  else if(v.title == '打印' || v.title.includes('打印')){
			    this.handlePrint();
			  }
			  else if(v.title == '关闭' || v.title.includes('关闭')){
			    this.XQdialogVisible = false;
			  }
			},

			// 确定更新有效期
			async TZXQSubmit() {
			  // 检查日期是否发生变化
			  if (!this.TZXQcurrentTable.manuDate && !this.TZXQcurrentTable.expyDate) {
			    this.$message.warning('请至少修改一个日期字段');
			    return;
			  }
			  
			  try {
			    this.loading = true;
			    
			    // 准备请求参数
			    const params = {
			      id: this.TZXQcurrentTable.id,
			      manuDate: this.TZXQcurrentTable.manuDate,
			      expyDate: this.TZXQcurrentTable.expyDate
			    };
			    
			    const res = await updateDate(params);
			    
			    if (res.code === 200) {
			      this.$message.success('有效期更新成功');
			      this.TZXQdialogVisible = false;
			      
			      // 可选：刷新批次数据
			      this.getBatchNumberData();
			    } else {
			      this.$message.error(res.message || '有效期更新失败');
			    }
			  } catch (error) {
			    console.error('更新有效期出错:', error);
			    this.$message.error('更新有效期出错');
			  } finally {
			    this.loading = false;
			  }
			},
			// input 
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.$refs['addForm'].resetFields();
					done();
				  })
				  .catch(_ => {
					
				  });
			},
			XQhandleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.XQdialogVisible = false;
					// this.$refs['addForm'].resetFields();
					done();
				  })
				  .catch(_ => {
					
				  });
			},
			TZXQhandleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					// this.$refs['addForm'].resetFields();
					done();
				  })
				  .catch(_ => {
					
				  });
			},
			flowhandleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					done();
				  })
				  .catch(_ => {
				});
			},
			// db events
			// 步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:
						// 处理索引0的逻辑 => 刷新
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
						break;
					case 1:
						// 处理索引1的逻辑
						this.$confirm('敬请期待')
							.then(_ => {})
							.catch(_ => {});
						break;
				}
			},
			// 打印按钮点击事件
			handlePrint() {
			  this.$confirm('请选择打印方式', '打印设置', {
			    confirmButtonText: 'Lodop打印',
			    cancelButtonText: '浏览器打印',
			    type: 'warning'
			  }).then(() => {
			    // 用户选择Lodop打印
				console.log('用户选择Lodop打印');
			    this.printWithLodop();
			  }).catch(() => {
			    // 用户选择浏览器打印
			    // this.printWithBrowser()
				console.log('用户选择浏览器打印');
			  })
			},
			// 使用Lodop打印并设计
			printWithLodop() {
			// if (!this.currentTable || this.currentTable.length === 0) {
			//     this.$message.warning('请先选择一条数据');
			//     return;
			//   }
			  
			  // 准备表格数据
			  const tableData = this.tableData.map(item => {
				return {
				  ...item,
				  // 添加任何需要转换的字段
				};
			  });
			  
			  // 准备当前选中行数据
			  const currentTable = this.currentTable;
			  
			  this.$router.push({
				path: '/PrintTemplateDesigner',
				query: {
				  tableData: JSON.stringify(tableData),
				  currentTable: JSON.stringify(tableData),
				  templateName: '【中药库】药品库存清单'
				}
			  });
			},
			// 生产日期变化处理
			handleManuDateChange(value) {
			  if (!value) return;
			  
			  // 如果有效期已设置且小于生产日期，提示用户
			  if (this.TZXQcurrentTable.expyDate && 
			      new Date(value) > new Date(this.TZXQcurrentTable.expyDate)) {
			    this.$message.warning('生产日期不能晚于有效日期');
			    this.TZXQcurrentTable.manuDate = ''; // 清空选择
			  }
			},
			
			// 有效日期变化处理
			handleExpyDateChange(value) {
			  if (!value) return;
			  
			  const currentDate = new Date();
			  const manuDate = this.TZXQcurrentTable.manuDate ? new Date(this.TZXQcurrentTable.manuDate) : null;
			  
			  // 检查是否小于当前日期
			  if (new Date(value) < currentDate) {
			    this.$message.warning('有效日期不能早于当前日期');
			    this.TZXQcurrentTable.expyDate = ''; // 清空选择
			    return;
			  }
			  
			  // 检查是否小于生产日期
			  if (manuDate && new Date(value) < manuDate) {
			    this.$message.warning('有效日期不能早于生产日期');
			    this.TZXQcurrentTable.expyDate = ''; // 清空选择
			  }
			},
			handleCommand(command) {
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '可用'
				  break;
				case 'b':
				  // 处理b的逻辑
				  console.log('执行B逻辑');
				  this.DropDownedName = '禁用'
				  break;
				case 'c':
				  // 处理b的逻辑
				  this.DropDownedName = '全部'
				  break;
				// ... 其他 case
			  }
			},
			// 实时宽度
			updateWindowWidth() {
				this.windowWidth = window.innerWidth - 228;
			},
			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			innerHandleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.getFlowData();
			},
			//当前条数改变触发
			innerHandleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.getFlowData();
			},
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .el-dialog__header{
		padding: 4px;
		background-color: #007bb0;
	}
	/deep/ .el-dialog__title{
		color: #fff;
		font-size: 12px;
	}
	/deep/ .el-dialog__headerbtn{
		top: 10px;
	}
	.box {
	  height: calc(100vh - 64px); // 减去导航栏高度
	  width: 100%;
	  overflow: hidden;
	
		/deep/ .el-table {
	    width: 100% !important;
	    
	    .el-table__body-wrapper {
	      overflow-x: auto !important;
	    }
	    
	    .el-table__header-wrapper {
	      overflow-x: hidden !important;
	    }
		/* 小眼睛图标样式 */
		.el-icon-watch {
		  color: #409EFF;
		  &:hover {
		    color: #66b1ff;
		  }
		}
		.el-icon-shield {
		  color: #F56C6C;
		  &:hover {
		    color: #f78989;
		  }
		}
	}
	/deep/ .el-switch__label *{
		font-size: 12px;
	}
	/deep/ .el-table .cell{
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}
	/deep/ .el-table th{
		font-size: 12px;
		background-color: #f1f1f1;
		border: none;
		color: #2d2d2d;
	}
	/deep/ .el-table {
	    width: 100%;
	    // height: 100% !important;
	    .el-table__body-wrapper {
	      overflow-x: hidden;
	    }
	}
	/* 自定义高亮颜色 */
	::v-deep .el-table__body tr.current-row > td {
	  background-color: #80b7ff !important;
	  color: #f9f9f9; /* 可选：修改文字颜色 */
	}
	  .main {
	    display: flex;
	    height: 100%;
	    width: 100%;
	
	    // 左侧树形菜单
	    .main-left {
	      width: 128px;
	      height: 100%;
	      background: #f5f7fa;
	      border-right: 1px solid #e6e6e6;
	      overflow-y: auto;
	      scrollbar-width: none; /* Firefox */
	      -ms-overflow-style: none; /* IE 10+ */
	      
	      &::-webkit-scrollbar {
	        display: none; /* Chrome Safari */
	      }
	
	      /deep/ .el-tree {
	        height: 100%;
	        .el-tree-node__content {
	          height: 36px;
	        }
	      }
	    }
	    
	    // 右侧内容区域
	    .main-right {
	      flex: 1;
	      display: flex;
	      flex-direction: column;
	      height: 100%;
	      overflow: hidden;
	      
	      // 顶部搜索区域
		.main-icon {
			display: flex;
			align-items: center;
			padding: 12px;
			line-height: 40px;
			.main-icon-a{
				// width: 240px;
				// background-color: #00557f;
			}
			.main-icon-b{
				margin-left: 28px;
				/deep/ .el-dropdown{
					font-size: 12px;
					cursor: pointer;
				}
				/deep/ .el-dropdown:hover {
					font-weight: bold;
					color: #66b1ff;
				}
				/deep/ .el-icon--right{
					// background-color: #66b1ff;
				}
				/deep/ .el-popper[x-placement^=bottom]{
					margin-top: 0;
				}
			}
			// c
			.main-icon-c{
				display: flex;
				align-items: center;
				margin-left: 28px;
				/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
					width: 80%;
				}
			}
		}
	      
		// 表格容器（带滚动）
		.table {
	        flex: 1;
			width: 100%;
	        overflow: hidden;
	        display: flex;
	        flex-direction: column;
			/deep/ .el-pagination {
				margin: 12px;
			}
	    }
	      
	      // 底部固定区域
	      .feet {
	        height: 40px;
	        display: flex;
			align-items: center;
	        padding: 12px;
	        background: #fff;
	        border-top: 1px solid #e6e6e6;
	        flex-shrink: 0;
	        
	        .feetBtn {
	          gap: 8px;
	        }
			
	        }
	    }
	  }
		.moreTool{
			/* 高级设置对话框样式 */
			/deep/ .el-dialog__header {
			  background-color: #007bb0;
			  padding: 12px;
			}
			
			/deep/ .el-dialog__title {
			  color: #fff;
			  font-size: 14px;
			}
			
			/deep/ .el-dialog__headerbtn .el-dialog__close {
			  color: #fff;
			}
			
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover {
			  background-color: brown;
			}
		}
		.addModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
		.editModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
	}

</style>